<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\model\AccountDailyStatModel;
use app\model\ClientAccountModel;
use app\model\CrontabTaskModel;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class AccountCostSortWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            //            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('account_cost_sort_work');
        $this->setDescription('账户表消耗排序字段');
        $this->addArgument('media_id', Argument::OPTIONAL, '媒体id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======账户表消耗排序字段开始' . date('Y-m-d H:i:s', time()) . '=======');
        $mediaId = intval($input->getArgument('media_id'));
        if ($mediaId) {
            $accounts = $this->getAccounts($mediaId);
        } else {
            $accounts = $this->getAccounts();
        }
        $statDate = intval(date('Ymd', strtotime('-2 days')));
        if ($accounts) {
            foreach ($accounts as $account) {
                $cost = $this->getAccountCost($account['id'], $statDate);
                $cost = $cost * 1000;
                if ($cost != $account['cost_sort']) {
                    $this->updateCost(intval($account['id']), intval($cost));
                }
            }
//            CrontabTaskService::setSingleTask($this);
        }

        $output->writeln('=======账户表消耗排序字段结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取账户id.
     */
    private function getAccounts(int $mediaId = 0)
    {
        $where = [];
        if ($mediaId > 0) {
            $where[] = ['media_id', '=', $mediaId];
        }
        return ClientAccountModel::where($where)->where('auth_valid', 1)->field('id,cost_sort')->order('id desc')->select();
    }

    /**
     * 获取账户消耗.
     */
    private function getAccountCost(int $accountId = 0, int $statDate = 0): float
    {
        return AccountDailyStatModel::where('account_id', $accountId)->where('stat_date', $statDate)->sum('cost');
    }

    /**
     * 更新数据.
     */
    private function updateCost(int $accountId = 0, int $cost = 0)
    {
        return ClientAccountModel::where('id', $accountId)->update(['cost_sort' => $cost]);
    }
}
